package cms_article

import (
	"encoding/json"
	"fmt"
	util2 "gitee.com/binny_w/go-util/v2"
	"github.com/gin-gonic/gin"
	"strings"
	"time"
)

func updateFixer(c *gin.Context, row *util2.MysqlRow) error {
	if row.IsEmpty() {
		return fmt.Errorf("提交数据为空")
	}
	if row.Has("title") {
		if strings.TrimSpace(row.ToStr("title")) == "" {
			return fmt.Errorf("标题不能为空")
		}
	}
	if row.Has("cover[bucket]") && row.Has("cover[key]") {
		if coverBs, err := json.Marshal([2]string{row.ToStr("cover[bucket]"), row.ToStr("cover[key]")}); err != nil {
			return err
		} else {
			row.Set("cover", string(coverBs))
		}
	}
	if row.Has("tags[]") {
		tags := row.ToStrings("tags[]")
		if tagsBs, err := json.Marshal(tags); err != nil {
			return err
		} else {
			row.Set("tags", string(tagsBs))
		}
	}
	if row.Has("deleted_at") {
		if row.ToInt64("deleted_at") > 0 {
			row.Set("deleted_at", time.Now().Unix())
		}
	}
	row1, _ := c.Get("user")
	user, _ := row1.(*util2.MysqlRow)
	row.Set("updated_at", time.Now().Unix())
	row.Set("updated_by", user.ToStr("name"))
	row.Drop("cover[bucket]", "cover[key]", "tags[]")
	return nil
}
